package com.example.springbootwork.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.springbootwork.entity.User;
import com.example.springbootwork.service.impl.UserServiceImpl;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

@Component
public class TokenUtil {

    private static final String secret = "dango";
    public String generateToken(User user){
        Date start = new Date();
        long currentTime = System.currentTimeMillis() + 60* 60* 1000;
        Date end = new Date(currentTime);
        String token = "";
        token = JWT.create()
                .withClaim("id", user.getId().toString())
                .withClaim("username", user.getUsername())
                .withClaim("role", new UserServiceImpl().getUserRole(user.getId()))
                .withIssuedAt(start)
                .withExpiresAt(end)
                .sign(Algorithm.HMAC256(secret));
        return token;
    }

    public Map parseToken(String token){
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(secret)).build().verify(token);
        Map<String, Claim> claims = verify.getClaims();
        return claims;
    }

}
